﻿using System;
using System.Globalization;
using AB.ServiceDirectory.BO;
using AB.ServiceDirectory.Design.WebUserControls.Frame;
using AB.ServiceDirectory.Entities;

namespace AB.ServiceDirectory.Design.Directorates
{
    public partial class DirectorateDetails : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadCountry();
                LoadDirectorateDetails();
                ViewState["OldName"] = TextBoxDirectorateName.Text;
            }

            LoadDepartmentList();
            LabelNameExists.Text = string.Empty;
        }

        /// <summary>
        /// Handles the Command event of the ButtonLookup control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.CommandEventArgs"/> instance containing the event data.</param>
        protected void ButtonLookup_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "contact":
                    ContactLookupPopup.Popup();
                    break;
                case "postcode":
                    AddressLookupPopup.Popup();
                    CheckBoxCopy.Checked = false;
                    HiddenFieldAddressId.Value = null;
                    TextBoxAddressLine1.Text = string.Empty;
                    TextBoxAddressLine2.Text = string.Empty;
                    TextBoxAddressLine3.Text = string.Empty;
                    TextBoxPostcode.Text = string.Empty;
                    break;
                case "business":
                    BusinessLookup.Popup();
                    break;
            }
        }

        /// <summary>
        /// Handles the CheckedChanged event of the CheckBoxCopy control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void CheckBoxCopy_CheckedChanged(object sender, EventArgs e)
        {
            var organisationId = 0;
            if (!int.TryParse(HiddenFieldOrganizationId.Value, out organisationId))
            {
                return;
            }

            var organisation = OrganizationBO.GetOrganizationById(organisationId);
            HiddenFieldAddressId.Value = CheckBoxCopy.Checked ? organisation.Address.AddressId.ToString(CultureInfo.CurrentCulture) : null;
            TextBoxAddressLine1.Text = CheckBoxCopy.Checked ? organisation.Address.AddressLine : string.Empty;
            TextBoxAddressLine2.Text = CheckBoxCopy.Checked ? organisation.Address.AddressLine2 : string.Empty;
            TextBoxAddressLine3.Text = CheckBoxCopy.Checked ? organisation.Address.AddressLine3 : string.Empty;
            TextBoxPostcode.Text = CheckBoxCopy.Checked ? organisation.Address.Postcode : string.Empty;
        }

        /// <summary>
        /// Handles the Command event of the ButtonSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.CommandEventArgs"/> instance containing the event data.</param>
        protected void ButtonSave_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
        {
            //ButtonSave.CommandName = !string.IsNullOrEmpty(HiddenFieldDirectorateId.Value) ? "edit" : "save";
            if (ButtonSave.CommandName == "new")
            {
                var directorate = GetDirectorate();
                directorate.DirectorateName = TextBoxDirectorateName.Text.Trim();

                if (DirectorateBO.CheckDirectorateName(directorate.DirectorateName))
                {
                    LabelNameExists.Text = "Directorate Name is duplicated";
                    return;
                }

                directorate.IsActive = true;
                DirectorateBO.AddDirectorate(directorate);
                Response.Redirect(string.Format(CultureInfo.CurrentCulture, "~/Organisation/OrganisationDetails.aspx?id={0}#DetailsPanel06", directorate.OrganizationId));
            }
            else if (ButtonSave.CommandName == "edit")
            {
                var directorate = GetDirectorate();
                var oldName = ViewState["OldName"] as string;
                if (oldName != directorate.DirectorateName)
                {
                    if (DirectorateBO.CheckDirectorateName(directorate.DirectorateName))
                    {
                        LabelNameExists.Text = "Directorate Name is duplicated";
                    }
                    directorate.DirectorateName = TextBoxDirectorateName.Text.Trim();
                }
                else
                {
                    directorate.DirectorateName = TextBoxDirectorateName.Text.Trim();
                }

                DirectorateBO.EditDirectorate(directorate);
                Response.Redirect(string.Format(CultureInfo.CurrentCulture, "~/Organisation/OrganisationDetails.aspx?id={0}#DetailsPanel06", directorate.OrganizationId));
            }
        }

        /// <summary>
        /// Handles the Command event of the ButtonInactive control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.CommandEventArgs"/> instance containing the event data.</param>
        protected void ButtonInactive_Command(object sender, System.Web.UI.WebControls.CommandEventArgs e)
        {
            var directorateId = int.Parse(HiddenFieldDirectorateId.Value, CultureInfo.CurrentCulture);
            DirectorateBO.SetDirectorateStatus(directorateId, false);
            ButtonInactive.Visible = false;
        }

        /// <summary>
        /// Handles the Click event of the ButtonBack control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void ButtonBack_Click(object sender, EventArgs e)
        {
            int organisationId;
            if (int.TryParse(HiddenFieldOrganizationId.Value, out organisationId))
            {
                Response.Redirect(string.Format(CultureInfo.CurrentCulture, "~/Organisation/OrganisationDetails.aspx?id={0}#DetailsPanel06", organisationId));
            }
        }

        /// <summary>
        /// Loads the country.
        /// </summary>
        private void LoadCountry()
        {
            DropDownListNationCounty.DataSource = CountryBO.SelectCountries();
            DropDownListNationCounty.DataBind();
        }

        /// <summary>
        /// Loads the department list.
        /// </summary>
        private void LoadDepartmentList()
        {
            int directorateId;
            if (int.TryParse(HiddenFieldDirectorateId.Value, out directorateId))
            {
                DetailsPanel02.Visible = true;
                LinkDetails02.Visible = true;

                var departmentListFrame =
                    (DepartmentListFrame)Page.LoadControl("~/WebUserControls/Frame/DepartmentListFrame.ascx");
                departmentListFrame.DirectorateId = directorateId;
                HolderDepartmentList.Controls.Clear();
                HolderDepartmentList.Controls.Add(departmentListFrame);
            }
        }

        /// <summary>
        /// Loads the directorate details.
        /// </summary>
        private void LoadDirectorateDetails()
        {
            int directorateId;
            int organisationId;

            if (int.TryParse(Request.Params["organisationId"], out organisationId))
            {
                var organisation = OrganizationBO.GetOrganizationById(organisationId);
                if (organisation == null)
                {
                    return;
                }

                ButtonSave.CommandName = "new";
                ButtonSave.Enabled = true;
                ButtonInactive.Visible = false;

                // Web address default from Organization
                TextBoxWebAddress.Text = organisation.WebAddress;

                // Type of business from Organization
                TextBoxSicCode.Text = organisation.BusinessType.SICCode;
                TextBoxTypeOfBusiness.Text = organisation.BusinessType.BusinessName;
                HiddenFieldBusinessId.Value = organisation.BusinessId.ToString(CultureInfo.CurrentCulture);

                // Address from Organization
                HiddenFieldAddressId.Value = organisation.AddressId.ToString(CultureInfo.CurrentCulture);
                TextBoxPostcode.Text = organisation.Address.Postcode;

                // Contact from Organization
                if (organisation.Contact != null)
                {
                    var contact = organisation.Contact;
                    TextBoxLeadContact.Text = string.Format(CultureInfo.CurrentCulture, "{0} {1}", contact.FirstName, contact.Surname);
                    HiddenFieldContactId.Value = organisation.ContactId.Value.ToString(CultureInfo.CurrentCulture);
                }

                HiddenFieldOrganizationId.Value = organisationId.ToString(CultureInfo.CurrentCulture);
            }
            else if (int.TryParse(Request.Params["directorateId"], out directorateId))
            {
                var directorate = DirectorateBO.GetDirectorateById(directorateId);
                if (directorate == null)
                {
                    return;
                }

                ButtonSave.CommandName = "edit";
                ButtonSave.Enabled = true;
                ButtonInactive.Visible = directorate.IsActive;

                HiddenFieldDirectorateId.Value = directorate.DirectorateId.ToString(CultureInfo.CurrentCulture);
                TextBoxDirectorateName.Text = directorate.DirectorateName;

                if (directorate.Contact != null)
                {
                    var contact = directorate.Contact;
                    HiddenFieldContactId.Value = contact.ContactId.ToString(CultureInfo.CurrentCulture);
                    TextBoxLeadContact.Text = string.Format(CultureInfo.CurrentCulture, "{0} {1}", contact.FirstName, contact.Surname);
                }

                if (directorate.Address != null)
                {
                    var address = directorate.Address;
                    TextBoxAddressLine1.Text = address.AddressLine;
                    TextBoxAddressLine2.Text = address.AddressLine2;
                    TextBoxAddressLine3.Text = address.AddressLine3;
                    DropDownListNationCounty.SelectedValue = directorate.CountryId;
                    TextBoxPostcode.Text = address.Postcode;
                    HiddenFieldAddressId.Value = address.AddressId.ToString(CultureInfo.CurrentCulture);
                }

                if (directorate.BusinessType != null)
                {
                    var business = directorate.BusinessType;
                    TextBoxSicCode.Text = business.SICCode;
                    TextBoxTypeOfBusiness.Text = business.BusinessName;
                    HiddenFieldBusinessId.Value = business.BusinessId.ToString(CultureInfo.CurrentCulture);
                }

                TextBoxFullDescription.Text = directorate.FullDescription;
                TextBoxShortDescription.Text = directorate.ShortDescription;
                TextBoxFax.Text = directorate.Fax;
                TextBoxEmail.Text = directorate.Email;
                TextBoxCounty.Text = directorate.County;
                TextBoxCityTown.Text = directorate.CityTown;
                TextBoxCharityNumber.Text = directorate.CharityNumber;
                TextBoxWebAddress.Text = directorate.WebAddress;
                TextBoxPhoneNumber.Text = directorate.PhoneNumber;
                TextBoxCompanyNumber.Text = directorate.CompanyNumber;
                HiddenFieldOrganizationId.Value = directorate.OrganizationId.ToString(CultureInfo.CurrentCulture);
            }
        }

        /// <summary>
        /// Gets the directorate.
        /// </summary>
        /// <returns></returns>
        private Directorate GetDirectorate()
        {
            int contactId;
            var directorate = new Directorate();
            if (ButtonSave.CommandName.Equals("edit"))
            {
                directorate.DirectorateId = int.Parse(HiddenFieldDirectorateId.Value, CultureInfo.CurrentCulture);
            }

            directorate.OrganizationId = int.Parse(HiddenFieldOrganizationId.Value, CultureInfo.CurrentCulture);
            directorate.ShortDescription = TextBoxShortDescription.Text;
            directorate.FullDescription = TextBoxFullDescription.Text;
            directorate.CityTown = TextBoxCityTown.Text;
            directorate.County = TextBoxCounty.Text;
            directorate.PhoneNumber = TextBoxPhoneNumber.Text;
            directorate.Fax = TextBoxFax.Text;
            directorate.Email = TextBoxEmail.Text;
            directorate.WebAddress = TextBoxWebAddress.Text;
            directorate.CharityNumber = TextBoxCharityNumber.Text;
            directorate.CompanyNumber = TextBoxCompanyNumber.Text;
            directorate.CountryId = DropDownListNationCounty.SelectedValue;
            directorate.ContactId = int.TryParse(HiddenFieldContactId.Value, NumberStyles.Integer, CultureInfo.CurrentCulture, out contactId)
                                        ? contactId
                                        : (int?)null;
            directorate.BusinessId = int.Parse(HiddenFieldBusinessId.Value, CultureInfo.CurrentCulture);
            directorate.AddressId = int.Parse(HiddenFieldAddressId.Value, CultureInfo.CurrentCulture);
            return directorate;
        }
    }

}